from django_community.config import ANONYMOUS_USERS_ENABLED
from django_community.models import UserOpenID, UserProfile
from django_community.utils import create_user_from_openid, get_anon_user

from django.core.exceptions import ObjectDoesNotExist

class CommunityMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            if request.openid:
                try:
                    user_open_id = UserOpenID.objects.get(openid = request.openid.openid)
                    request.user = user_open_id.user
                except ObjectDoesNotExist:
                    request.user = create_user_from_openid(request, request.openid)
        if not request.user.is_authenticated() and ANONYMOUS_USERS_ENABLED:
            request.user = get_anon_user(request)
        request.user.profile = UserProfile.objects.get_user_profile(request.user)